package com.example.websocket.executor;

import java.util.Random;
import java.util.concurrent.*;

// 固定数量的线程池
public class FixedThreadPool {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        // 添加任务方式1
        threadPool.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("有返回值");
                System.out.println(Thread.currentThread().getName());
            }
        });
        // 添加任务方式2
        threadPool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("无返回值");
                System.out.println(Thread.currentThread().getName());
            }
        });
        // 有返回结果
        Future<Integer> result = threadPool.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int num = new Random().nextInt(10);
                System.out.println("随机数" + num);
                System.out.println(Thread.currentThread().getName());
                return num;
            }
        });
        System.out.println("返回结果：" + result.get());
        threadPool.shutdown();

        ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                // 一定要注意：要把任务Runnable设置给新创建的线程
                Thread thread = new Thread(r);
                // 设置线程的命名规则
                thread.setName("我的线程" + r.hashCode());
                // 设置线程的优先级
                thread.setPriority(Thread.MAX_PRIORITY);
                return thread;
            }
        };

        threadPool = Executors.newFixedThreadPool(2, threadFactory);
        Future<Integer> result1 = threadPool.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int num = new Random().nextInt(10);
                System.out.println(Thread.currentThread().getName());
                System.out.println(Thread.currentThread().getPriority() + "，随机数" + num);
                return num;
            }
        });
        System.out.println("返回结果：" + result1.get());
        // 1、设置线程的命名规则。
        // 2、设置线程的优先级。
        // 3、设置线程分组。
        // 4、设置线程类型（用户线程、守护线程）。
    }
}
